package com.fluvet.zts.service.impl;

import com.fluvet.zts.model.SkywalkingSpan;
import com.fluvet.zts.model.ZipkinSpan;
import com.fluvet.zts.repository.ISkywalkingClient;
import com.fluvet.zts.service.IApiService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

@Service
public class ApiServiceImpl implements IApiService {

    @Resource
    ISkywalkingClient iSkywalkingClient;

    @Override
    public boolean transform(ZipkinSpan zipkinSpan) {

        ArrayList<SkywalkingSpan.SpansDTO> spans = new ArrayList<>();

        Map<String, String> tagsMap = zipkinSpan.getTags();
        String statusCode = tagsMap.get("http.status_code");
        String upstreamCluster = tagsMap.get("upstream_cluster");
        String url = tagsMap.get("http.url");

        ArrayList<SkywalkingSpan.SpansDTO.TagsDTO> tags = new ArrayList<>();
        Set<String> keySet = tagsMap.keySet();
        for (String key : keySet) {
            SkywalkingSpan.SpansDTO.TagsDTO e = new SkywalkingSpan.SpansDTO.TagsDTO();
            e.setKey(key);
            e.setValue(tagsMap.get(key));
            tags.add(e);
        }
        long startTime = zipkinSpan.getTimestamp() / 1000;
        SkywalkingSpan.SpansDTO entrySpan = SkywalkingSpan.SpansDTO.builder()
                .operationName(upstreamCluster)
                .startTime(startTime)
                .endTime((zipkinSpan.getTimestamp() + zipkinSpan.getDuration()) / 1000)
                .spanType("Entry")
                .spanId(0)
                .parentSpanId(-1)
                .isError(ObjectUtils.isEmpty(statusCode) || !statusCode.startsWith("2"))
                .spanLayer("Http")
                .componentId(6000)
                .peer(url)
                .tags(tags)
                .build();
        spans.add(entrySpan);

        SkywalkingSpan skywalkingSpan = new SkywalkingSpan(zipkinSpan.getTraceId(), zipkinSpan.getLocalEndpoint().getServiceName(), spans
                , zipkinSpan.getLocalEndpoint().getServiceName(), zipkinSpan.getTraceId());

        iSkywalkingClient.save(skywalkingSpan).subscribe();
        return true;
    }

}
